package com.ljq.cksp.service.impl;

import com.ljq.cksp.dao.UserDAO;
import com.ljq.cksp.pojo.User;
import com.ljq.cksp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @Author:ljq
 * @Date:2020/2/24
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDAO userDAO;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public Page<User> listUser(int start, int size){
        start = start<0?0:start;
        return userDAO.findAll(PageRequest.of(start, size, Sort.by(Sort.Direction.ASC, "role", "id")));
    }

    @Override
    public boolean nameIsExist(String username) {
        return userDAO.findByName(username) != null;
    }

    @Override
    public boolean validate(String username, String password) {
        return userDAO.findByNameAndPassword(username, password) != null;
    }

    @Override
    public boolean sendMail(String content) {
        return false;
    }

    @Override
    public void delete(int id){
        userDAO.deleteById(id);
    }

    @Override
    public void save(User user) {
        userDAO.save(user);
    }

    @Override
    public void register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRole("ROLE_USER");
        userDAO.save(user);
    }

    @Override
    public void addAdmin(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRole("ROLE_ADMIN");
        userDAO.save(user);
    }

    @Override
    public User modify(int id, User user) {
        User old = userDAO.findById(id);
        user.setId(id);
        user.setPassword(old.getPassword());
        userDAO.save(user);
        return user;
    }

    @Override
    public User modifyPassword(int id, String password) {
        User user = userDAO.findById(id);
        user.setPassword(passwordEncoder.encode(password));
        userDAO.save(user);
        return user;
    }

    @Override
    public User findByName(String username) {
        return userDAO.findByName(username);
    }

    @Override
    public User findById(int id) {
        return userDAO.findById(id);
    }

    @Override
    public User findByEmail(String email) {
        return userDAO.findByEmail(email);
    }
}
